package com.bw.utils;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

public class DimUtil {
    public static JSONObject getDimInfo(Connection connection, String tableName, String id) throws Exception {
        // 缓存Redis
        Jedis jedis = RedisUtil.getJedis();
        // 拼接出KEY
        String key = "DIM:" + tableName + ":" + id;
        String value = jedis.get(key);
        if (value != null) {
            // 重新设置24小时到期
            jedis.expire(key, 24 * 60 * 60);
            // 归还连接
            jedis.close();
            return JSONObject.parseObject(value);
        } else {
            // 编写SQL
            String sql = "select * from " + GmallConfig.HBASE_SCHEMA + "." + tableName + " where id = '" + id + "'";
            // 查询维度
            List<JSONObject> jsonObject = JdbcUtil.queryList(connection, sql, JSONObject.class, false);

            // 返回维度
            JSONObject dimJson = jsonObject.get(0);
            // 查询到放到redis做缓存
            jedis.set(key, dimJson.toJSONString());
            // 设置过期时间
            jedis.expire(key, 24 * 60 * 60);
            // 归还连接
            jedis.close();
            // 把维度信息返回
            return dimJson;
        }
    }

    // 删除redis中的维度数据
    public static void deleteDimForRedis(String key) {
        Jedis jedis = RedisUtil.getJedis();
        jedis.del(key);
        jedis.close();
    }

    public static void main(String[] args) throws Exception {
        Class.forName(GmallConfig.PHOENIX_DRIVER);
        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
        String user_id = "700";
        Long start = System.currentTimeMillis();
        JSONObject dim_user_info = getDimInfo(connection, "DIM_USER_INFO", user_id);
        System.out.println(dim_user_info);
        Long end = System.currentTimeMillis();
        System.out.println(end - start);


//        JSONObject dim_user_info1 = getDimInfo(connection, "DIM_USER_INFO", user_id);
//        Long end1 = System.currentTimeMillis();
//        System.out.println(end1 - end);


        Long start1 = System.currentTimeMillis();
//        getDimInfo(null, "DIM_USER_INFO", "700");
        Long end1 = System.currentTimeMillis();
        System.out.println(end1 - start1);


        Long start2 = System.currentTimeMillis();
//        getDimInfo(null, "DIM_USER_INFO", "700");
        Long end2 = System.currentTimeMillis();
        System.out.println(end2 - start2);

    }
}
